package iscte.iul.dcti.pa.al2011_12.model;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;

public class Cell extends Observable {
	private int abscissa;		//XX
	private int ordinate;			//YY
	private String value;
	private List<Cell> referredCells;
	private List<Character> operators;
	
	//private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
	
	public Cell () {	//deriva de observale
	}
	
	public Cell(int abscissa, int ordinate) {
		super();
		this.abscissa = abscissa;
		this.ordinate = ordinate;
		this.value = "";
		this.referredCells = new ArrayList<Cell>();
		this.operators = new ArrayList<Character>();
	}
		
	public int getAbscissa() {
		return abscissa;
	}
	
	public int getOrdinate() {
		return ordinate;
	}
	
	public String getValue() {
		return value;
	}
	
	public void setValue(String value) {
		
		this.value = value;
		//propertyChangeSupport.firePropertyChange("value", this.value, this.value = value);
		setChanged();
		notifyObservers();
	}
	
	@Override
	public String toString() {
		//return "Abscissa: " + abscissa + "; Ordinate: " + ordinate + "; Value: " + value + ";";
		//return abscissa + "" + ordinate + ": " + value;
		return value;
	}
	
	public void addReferrerCell(Character operator, Cell cell) {
		operators.add(operator);
		referredCells.add(cell);
	}
	
	public void addReferrerCell(Cell cell) {
		referredCells.add(cell);
	}
	
	public String doMath() {
		int idx = -1;
		int res = 0;
		for (Cell cell : referredCells) {
			if (idx > -1) {
				switch (operators.get(idx)) {
				case '+':
					res += Integer.parseInt(cell.value);
					break;
				case '-':
					res -= Integer.parseInt(cell.value);
					break;
				case '*':
					res *= Integer.parseInt(cell.value);
					break;
				case '/':
					res /= Integer.parseInt(cell.value);
					break;
				case '%':
					res %= Integer.parseInt(cell.value);
					break;
				default:
					break;
				}
			}
			else {
				res = Integer.parseInt(cell.value);
			}
			idx++;
		}
		return Integer.toString(res);
	}
	
	public List<Cell> getReferredCells() {
		return referredCells;
	}
}
